#include <X11/Xlib.h>
#include "game.h"
#include <stdio.h>
#include <stdbool.h>

int main(void) {
    Game game = game_init();
    
    Display *display = XOpenDisplay(NULL);
    Window window = XCreateSimpleWindow(display,
        XDefaultRootWindow(display),
        0,0,
        game.display_width, game.display_height,
        0,
        0,
        0
    );

    XWindowAttributes wa = {0};
    XGetWindowAttributes(display, window, &wa);
    
    XImage *image = XCreateImage(
        display,
        wa.visual,
        wa.depth,
        ZPixmap,
        0,
        (char*)game.display,
        game.display_width,
        game.display_height,
        32,
        game.display_width * sizeof(*game.display)
    );

    GC gc = XCreateGC(display, window, 0, NULL);

    Atom wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(display, window, &wm_delete_window, 1);

    XSelectInput(display, window, KeyPressMask | PointerMotionMask);
    XStoreName(display, window, "The game");
    XMapWindow(display, window);

    bool quit = false;
    while (!quit) {
        while (XPending(display) > 0) {
            XEvent event = {0};
            XNextEvent(display, &event);
            switch(event.type) {
                case KeyPress: {
                    switch(XLookupKeysym(&event.xkey, 0)) {
                        case 'q':
                        quit = 1;
                        break;
                    }
                }
                break;
                case MotionNotify: {

                }
                break;
                case ClientMessage: {
                    if ((Atom) event.xclient.data.l[0] == wm_delete_window) {
                        quit = 1;
                    }
                }
                break;

                default: {}
                break;
            }
        }

        XPutImage(display, window, gc, image, 0,0,0,0,game.display_width, game.display_height);
    }
    return 0;
}